import { Form, message, Tabs, Modal } from 'antd';
import { history } from 'umi';
import { WorkflowSwitchContext } from '../common';
import { WorkflowNodesView } from './WorkflowNodesView';
import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useEffect, useMemo, useRef, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
import Cls from 'classnames';
import { WorkflowNodesImage } from './WorkflowNodesImage';
// import { SwapOutlined } from '@ant-design/icons';
import { WorkflowSwitchAPI } from '../common/type';
import '../common/styles.less';
import { getPosIDs, getTenantID, onCloseModalCommon } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { getUserListByOrgSrv, HandleFlowStateCommon, startProcessService } from '../services';
import { splitDealId } from '../mconfig';
import { getUserDataList } from '@/services/BaseLayout';
import { QuestionCircleOutlined } from '@ant-design/icons';

export const WorkflowSwitchModal: React.FC<WorkflowSwitchAPI.IWorkflowSwitchModal> = ({
  openVisible, //是否打开
  orderType, //业务类别
  category, // 总 流程类别
  businessCategory, // 相关业务 的流程类别
  requestController, //后端业务 Controller
  businessInfoObj, //选中的行数据
  selectFlowID, //选中的非默认流程id
  replaceStrObj = {}, //替换字段
  workFlowName = '',
  procdefFlag = false, //获取节点接口需要多一个参数name
  reloadInfoCallback, //发起流程后刷新管理页回调
  onSure, //点击确定按钮触发
  onClose, //关闭当前组件
  openFlowChangeModal, //打开切换非默认流程 modal
  startWorkFlowCallback,
  implementJumpCallback, //实施管理跳转回调
}) => {
  /** 解构 */
  const { own = 'own', procDefID = 'procDefID', workflowType = 'workflowType' } = replaceStrObj;

  /** 样式根节点 */
  const prefixCls: string = 'workflow-switchroot-';

  /** 流程节点ref */
  const workflowNodeRef = useRef<any>();

  /** modal ref */
  const WorkflowModalRef: Ref<IOneModalRef> = useRef(null);

  /** 保存当前流程id */
  const [saveProcessID, setSaveProcessID] = useState<string>(selectFlowID);

  /** 保存流程节点数据 */
  const [openFlowSuccess, setOpenFlowSuccess] = useState<string>('');

  /**  表单实例 */
  const [WorkflowSwitchForm] = Form.useForm();

  /** 保存流程节点LOADING */
  const [flowNodesLoading, setFlowNodesLoading] = useState<boolean>(true);

  /** 根据岗位获取人 */
  const { getUserRun, getUserLoading, getUserList, pramsObjInfo } = getUserDataList(() => {}); //userPositionID: "102030502"

  /**
   * 处理流程提交成功信息    taskIsSign 【是否会签(0: 普通任务 1: 会签任务)】
   * @param flowList 传入接口流程数据
   * @param nodeList 流程节点数据
   */
  const handOpenFlowMessage = (flowList: Record<string, any>[], nodeList: Record<string, any>[]) => {
    let msgStr: string[] = [];
    let msgType: string = '';
    const flowInfo: Record<string, any> | undefined = flowList?.find((itemFlow: any) => itemFlow?.seq == 2);
    const nodeInfo: Record<string, any> | undefined = nodeList?.find((itemFlow: any) => itemFlow?.seq == 2);
    const nodeDealInflList: Record<string, any>[] = splitDealId(nodeInfo?.postDealerID, nodeInfo?.postDealerName);
    if (flowInfo?.taskIsSign == 0) {
      msgType = '办理';
      const [_flowPostId, flowUserId] = flowInfo?.postDealerID?.split('|');
      const userNae: string | any = nodeDealInflList?.find((item: any) => flowUserId == item?.dealUserId)?.dealUserName;
      msgStr?.push(userNae);
    } else {
      msgType = '会签';
      const flowdDealList: Record<string, any> = splitDealId(flowInfo?.postDealerID, '');
      flowdDealList?.forEach((item: any) => {
        const dealNameInfo: Record<string, any> | any = nodeDealInflList?.find((itemNode: any) => item?.dealUserId == itemNode?.dealUserId);
        msgStr?.push(dealNameInfo?.dealUserName);
      });
    }
    setOpenFlowSuccess(`已提交至【${msgStr?.toString()}】等处${msgType}`);
  };

  const { confirm } = Modal;

  /** 重新加载提示 */
  const reloadContact = (msg: string) => {
    confirm({
      title: '提示',
      icon: <QuestionCircleOutlined />,
      content: msg,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        reloadInfoCallback();
      },
      onCancel() {},
    });
  };

  const handOpenFlowMessage_copy = (flowList: Record<string, any>[], nodeList: Record<string, any>[]) => {
    const user = flowList?.find((item) => item?.dealPositionID != getPosIDs() || item?.taskIsSign != '2');
    const userPositionID = user?.dealPositionID;
    const userID = user?.dealerID;

    getUserRun({ userPositionID })?.then((res) => {
      if (res?.msgFlag) {
        let { rows } = res;
        if (rows && rows?.length) {
          let msgStr: string[] = [];
          let msgType: string = '';
          const userInfo = rows?.find((item) => item?.id == userID);
          if (nodeList?.[0]?.taskIsSign == 0) {
            msgType = '办理';
          } else {
            msgType = '会签';
          }
          msgStr?.push(userInfo?.realName);
          setOpenFlowSuccess(`已提交至【${msgStr?.toString()}】等处${msgType}`);
        }
      }
    });
  };

  /**
   *  开启流程回调
   * @param res
   */
  const startProcessCallBack = (res: any) => {
    if (res && res?.msgFlag) {
      message?.success(openFlowSuccess);
      reloadInfoCallback();
      onCloseModalCommon(WorkflowModalRef);
      if (startWorkFlowCallback) {
        startWorkFlowCallback();
      }

      // message.success(openFlowSuccess).then(() => {
      //   reloadInfoCallback();
      //   if (startWorkFlowCallback) {
      //     startWorkFlowCallback();
      //   }
      //   onCloseModalCommon(WorkflowModalRef);
      // });
      // if (implementJumpCallback) {
      //   implementJumpCallback();
      // }
    } else {
      if (!res?.versionFlag) {
        onCloseModalCommon(WorkflowModalRef);
        reloadContact(res?.msg);
      }
      message.error(res?.msg);
    }
  };

  /** 引入发起流程 */
  const { startProcessRun, startProcessLoading } = startProcessService(startProcessCallBack, requestController, own);

  /** 发起审批流程 */
  const onOk = () => {
    if (onSure) {
      onSure();
    }

    WorkflowSwitchForm?.validateFields()?.then((formData: any) => {
      const workFlowNodes: Record<string, any>[] = workflowNodeRef?.current?.workflowNodesList;
      let paramObject: Record<string, any>[] = []; //存储节点中的数据

      workFlowNodes?.forEach((itemNode: any, nodeIndex: number) => {
        let dealPostList: string[] = []; //存储办理岗位 id
        let postUserIDlist: string[] = []; //存储历史  岗位|人 id
        let dealUserList: string[] = []; //存储办理人 id

        // 遍历节点中所有的岗位节点
        itemNode?.postValues?.forEach((_itemChild: any, childIndex: number) => {
          if (formData['paramObject[' + nodeIndex + '].dealPositionID[' + childIndex + ']']) {
            dealPostList?.push(`${formData['paramObject[' + nodeIndex + '].dealPositionID[' + childIndex + ']']}`);
          }
          if (
            formData['paramObject[' + nodeIndex + '].dealPositionID[' + childIndex + ']'] &&
            formData['paramObject[' + nodeIndex + '].dealerID[' + childIndex + ']']
          ) {
            postUserIDlist?.push(
              `${formData['paramObject[' + nodeIndex + '].dealPositionID[' + childIndex + ']']}|${
                formData['paramObject[' + nodeIndex + '].dealerID[' + childIndex + ']']
              }`,
            );
          }

          if (formData['paramObject[' + nodeIndex + '].dealerID[' + childIndex + ']']) {
            dealUserList?.push(`${formData['paramObject[' + nodeIndex + '].dealerID[' + childIndex + ']']}`);
          }
        });
        console.log('dealPostList,postUserIDlist,dealUserList', dealPostList, postUserIDlist, dealUserList);

        if (
          (!businessInfoObj.relateDepartmentID && formData['paramObject[' + nodeIndex + '].taskName'].indexOf('本单位归口') > -1) ||
          (!businessInfoObj.busiDepartmentID &&
            formData['paramObject[' + nodeIndex + '].taskName'].indexOf('归口') > -1 &&
            formData['paramObject[' + nodeIndex + '].taskName'].indexOf('本单位归口') < 0 &&
            formData['paramObject[' + nodeIndex + '].taskName'] !== '办公室主任归口审批' &&
            businessCategory?.indexOf(`${getTenantID()}${ILoadMapTypeAll.PURAPPLY_APPLY}`) < 0) ||
          (!businessInfoObj.relateDepartmentID && formData['paramObject[' + nodeIndex + '].taskName'].indexOf('相关') > -1) ||
          (businessInfoObj?.allotType == 1 &&
            (formData['paramObject[' + nodeIndex + '].taskName'].indexOf('接收方部门/团队资管员审批') > -1 ||
              formData['paramObject[' + nodeIndex + '].taskName'].indexOf('接收方部门/团队领导审批') > -1)) ||
          (businessInfoObj?.assetStorageMaterialType == '0' && formData['paramObject[' + nodeIndex + '].taskName'].indexOf('资产专责复核') > -1) ||
          ((businessInfoObj?.businessType == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1011` ||
            businessInfoObj?.businessType == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1013`) &&
            businessInfoObj?.applyType == 2 &&
            formData['paramObject[' + nodeIndex + '].taskName'].indexOf('财务资产部专责复核') > -1) ||
          (businessInfoObj?.materialType == 0 && formData['paramObject[' + nodeIndex + '].taskName'].indexOf('资产入库') > -1) ||
          (businessInfoObj?.materialType == 1 && formData['paramObject[' + nodeIndex + '].taskName'].indexOf('材料入库') > -1)
        ) {
        } else {
          paramObject.push({
            dealPositionID: dealPostList?.length > 0 ? dealPostList?.toString() : null,
            postDealerID: postUserIDlist?.length > 0 ? postUserIDlist?.toString() : null,
            dealerID: dealUserList?.length > 0 ? dealUserList?.toString() : null,
            taskIsSign: formData['paramObject[' + nodeIndex + '].taskIsSign'],
            seq: formData['paramObject[' + nodeIndex + '].seq'],
            procDefID: formData['paramObject[' + nodeIndex + '].procDefID'],
            orderID: formData['paramObject[' + nodeIndex + '].orderID'],
            taskNode: formData['paramObject[' + nodeIndex + '].taskNode'],
            dealerNum: formData['paramObject[' + nodeIndex + '].dealerNum'],
            taskName: formData['paramObject[' + nodeIndex + '].taskName'],
          });
        }
      });

      /** 处理状态之间的转变 */
      const stateObj: Record<string, any> = HandleFlowStateCommon(businessInfoObj?.state, orderType);

      /**处理流程成功接口提示 */
      // handOpenFlowMessage(paramObject, workflowNodeRef?.current?.workFlowNodes);
      handOpenFlowMessage_copy(paramObject, workflowNodeRef?.current?.workFlowNodes);

      console.log('paramObject', paramObject);

      const params: Record<string, any> = {
        // workflowType: businessInfoObj?.workflowType,
        // category: category,
        paramObject: paramObject,
        [procDefID]: saveProcessID,
        [workflowType]: category,
        orderType,
        businessType: businessInfoObj?.businessType,
        createDepartmentID: businessInfoObj?.createDepartmentID,
        createPositionID: businessInfoObj?.createPositionID,
        createrID: businessInfoObj?.createrID,
        checkState: `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1000`,
        ...stateObj,
        id: businessInfoObj?.id,
        versionNum: businessInfoObj?.versionNum,
        inventoryID: businessInfoObj.inventoryID,
      };

      startProcessRun(params);
    });
  };

  /**
   * 获取用户信息回调
   * @param res
   */
  const loadUserByPosCallBack = (res: any) => {
    if (!(res && res?.msgFlag)) {
      message.error(res?.msg);
    }
  };

  /**  获取用户信息 */
  const { loadUserRun, loadUserLoading, loadUserData } = getUserListByOrgSrv(loadUserByPosCallBack);

  /** 处理Tabs页面  */
  const tabsPaneItems = useMemo(() => {
    return [
      {
        label: '流程节点设置',
        key: 'ProcessNodeSettings',
        children: (
          <WorkflowNodesView
            switchFlowObj={{ processID: selectFlowID }}
            changeProcessID={setSaveProcessID}
            ref={workflowNodeRef}
            loadUserRun={loadUserRun}
            loadUserData={loadUserData}
            loadUserLoading={loadUserLoading}
            setFlowNodesLoading={setFlowNodesLoading}
          />
        ),
      },
      {
        label: '流程图',
        key: 'ProcessNodeChrat',
        children: <WorkflowNodesImage workflowID={saveProcessID} />,
      },
    ];
  }, [WorkflowSwitchForm, saveProcessID, workflowNodeRef, loadUserLoading]);

  return (
    <WorkflowSwitchContext.Provider
      value={{
        prefixCls,
        openVisible, //是否打开
        orderType, //业务类别
        category, // 相关业务 的流程类别
        businessCategory, // 总 流程类别
        requestController,
        reloadInfoCallback,
        businessInfoObj,
        onClose,
        nodeFlowForm: WorkflowSwitchForm,
        workFlowName,
        procdefFlag,
      }}
    >
      <OneModal
        open={true}
        getContainer={false}
        ref={WorkflowModalRef}
        title={'发起审批'}
        width={document.body.clientWidth * 0.6}
        // width={document.body.clientWidth * 0.2}
        bodyStyle={{
          padding: '0px',
        }}
        centered
        onCancel={onClose}
        confirmLoading={loadUserLoading || startProcessLoading || flowNodesLoading}
        onOk={onOk}
        // footer={
        //   <div
        //     style={{
        //       display: 'flex',
        //       // justifyContent: 'space-between',
        //       justifyContent: 'flex-end',
        //     }}
        //   >
        //     {/* <div>
        //       <Button
        //         type={'primary'}
        //         icon={<SwapOutlined />}
        //         onClick={() => {
        //           onCloseModal();
        //           openFlowChangeModal(true);
        //         }}
        //       >
        //         使用非默认流程
        //       </Button>
        //     </div> */}
        //     <div>
        //       <Button
        //         onClick={() => {
        //           onCloseModal();
        //         }}
        //       >
        //         取消
        //       </Button>
        //       <Button type={'primary'} onClick={onOk} loading={ loadUserLoading||startProcessLoading ||flowNodesLoading}>
        //         确定
        //       </Button>
        //     </div>
        //   </div>
        // }
      >
        {/* <Spin spinning={loadUserLoading || startProcessLoading || flowNodesLoading}> */}
        <Form
          // style={{ display: 'none' }}
          form={WorkflowSwitchForm}
          className={prefixCls + 'workflowFormBox'}
        >
          <Tabs className={Cls(pageStyles['commonTabs'], prefixCls + 'workflowTabsBox')} type="card" items={tabsPaneItems} />
        </Form>
        {/* <div
            style={{
              textAlign: 'center',
              padding: '20px 0px',
              fontSize: '20px',
              fontWeight: 600,
              width: '100%',
              // color: 'red',
            }}
          >
            请确认是否发起审批流程？
          </div> */}
        {/* </Spin> */}
      </OneModal>
    </WorkflowSwitchContext.Provider>
  );
};
